﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Golos.Polls.PollCache;
using Golos.Web.Utils;

namespace Golos.Web.handlers
{
    public class GetPollHandler : HandlerBase
    {
        public GetPollHandler(HttpContext httpContext)
            : base(httpContext)
        {
        }

        public override void Handle()
        {
            try
            {
                Guid questionId = new Guid(GetQueryParam("qid"));

                Token token = TokenUtils.FromCookies(_httpContext.Request.Cookies);

                string json = "{";

                if (token != null)
                {
                    UserAnswerInfo userAnswerInfo = PollsClient.GetUserAnswerInfo(questionId, token.User);

                    if (userAnswerInfo != null)
                    {
                        json += PollsHelper.GetVotedPollInfo(token.User, questionId);
                    }
                    else
                    {
                        json += PollsHelper.GetPollInfo(questionId);
                    }
                }
                else
                {
                    json += PollsHelper.GetPollInfo(questionId);
                }

                json = json.TrimEnd(new char[] { ',', ' ' }) + "}";

                _httpContext.Response.Write(json);
            }
            catch (Exception e)
            {
                LogClass.WriteErrorEntry(e.ToString());
                _httpContext.Response.Write("{ \"error\": \"Не удалось получить опросов.\" }");
            }
        }
    }
}